package punch.job;

import cc.chenwenxi.api.commons.entity.timesheet.PunchType;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import punch.client.Cli;

import java.io.IOException;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
@RequiredArgsConstructor
public class Task {

    private void toPunch(PunchType type) throws IOException {
        Date now = new Date();
        String day = DateUtil.formatDate(now);
        Cli cli = new Cli();

        int i = RandomUtil.randomInt(5);
        if (type == PunchType.in) {
            String format = StrUtil.format("{}准备:{},等待:{}", type.getCn(), day, i);
            log.info(format);
            ThreadUtil.sleep(i, TimeUnit.MINUTES);
            cli.in();
        } else {
            String format = StrUtil.format("{}准备:{},等待:{}分钟", type.getCn(), day, i);
            log.info(format);
            ThreadUtil.sleep(i, TimeUnit.MINUTES);
            cli.out();
        }
        log.info("完成");
    }

    @Scheduled(cron = "0 40 18 ? * 1-5")
    public void out() {
        try {
            this.toPunch(PunchType.out);
        } catch (Exception e) {
        }
    }

    @Scheduled(cron = "0 5 9 ? * 1-5")
    public void in() {
        try {
            this.toPunch(PunchType.in);
        } catch (Exception e) {
        }
    }
}
